//index.js
//获取应用实例
var app = getApp();
Page({
  data: {
    showLoading: true,
    noMoretip: false,
    page: 0,
    showLocationtip:false,
    locationTips:'正在定位中，请耐心等待~'
  },
  onLoad: function (e) {
    var that = this;
    if(e){
      if (e.title) {
        app.setNavtitle(e.title);
        that.setData({
          title: e.title
        })
      } else {
        app.setNavtitle('门店');
      }
    }
    var location = app.globalData.location;
    if (location && location.lat) {
      that.setData({
        curChooseLatitude: location.lat,
        curChooseLongitude: location.lng
      })
      that.requestShoplist();
      app.getCurAddress(location.lat, location.lng, that);//获取当前地址
    }else{
      that.getLocation();
    }
    that.requestShopCategory();
  },
  onShow: function () {
    app.setNavtitle('门店');
    
    app.contactData(this); 
    this.setData({
      customerService: app.globalData.customerService,
      sessionForm: app.globalData.sessionForm ? app.globalData.sessionForm:''
    })
    console.log(this.data.customerService);
    app.setCartnum();//更新购物车数量
  },
  // 客服回复组件间传值
  getreplyData: function (e) {
    console.log(e.detail);
    this.setData(e.detail);
  },
  getLocation:function(e){
    var that = this;
    that.setData({
      showLocationtip:true
    })
    wx.getLocation({
      success: function (res) {
        console.log(res);
        that.setData({
          curChooseLatitude: res.latitude,
          curChooseLongitude: res.longitude,
          showLocationtip: false
        })
        var location = {
          lat: res.latitude,
          lng: res.longitude
        }
        app.globalData.location = location;
        that.requestShoplist();
        app.getCurAddress(res.latitude, res.longitude,that);//获取当前地址
      },
      fail: function () {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userLocation']) {
              that.setData({
                locationTips: "无法获取您的当前定位地址，请打开定位权限"
              })
            }else{
              wx.openSetting({
                success: (res) => {
                  res.authSetting = {
                    "scope.userLocation": true
                  }
                  console.log(res.authSetting);
                  that.onPullDownRefresh();
                }
              })
            }
          }
        })
      },
      complete: function () {
        // wx.hideLoading(); 
      }
    })
  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        var curLocation = res.name ? res.name : res.address;
        that.setData({
          curLocation: curLocation,
          curChooseLatitude: res.latitude,
          curChooseLongitude: res.longitude,
          curShopCategory: '',
          showLocationtip: false
        })
        var location = {
          lat: res.latitude,
          lng: res.longitude
        }
        app.globalData.location = location;
        that.requestShoplist();
      },
      fail: (res) => {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userLocation']) {
              that.setData({
                locationTips: "无法获取您的当前定位地址，请打开定位权限"
              })
            } else {
              wx.openSetting({
                success: (res) => {
                  res.authSetting = {
                    "scope.userLocation": true
                  }
                  console.log(res.authSetting);
                  that.onPullDownRefresh();
                }
              })
            }
          }
        })
      }
    })
  },
  searchKeyChange: function (e) {
    var that = this;
    that.setData({
      searchTxt: e.detail.value
    })
    console.log(that.data.searchTxt);
  },
  submitSearch: function () {
    var that = this;
    var searchTxt = that.data.searchTxt;
    that.setData({
      isKeyword: true,
      page: 0,
      noMoretip: false,
      showLoading: true
    })
    wx.showLoading({
      title: '搜索中',
      mask: true,
      time: 10000
    })
    that.requestShoplist(searchTxt);
  },
  focusChange:function(){
    var that = this;
    that.setData({
      showSearchbtn:true
    })
  },
  blurChange: function () {
    var that = this;
    that.setData({
      showSearchbtn: false
    })
  },
  requestShopCategory: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_cake_store_category'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var categoryList = app.splitArrData(res.data.data, 8);
          that.setData({
            shopCategory: categoryList
          })
        } else {
          console.log(res.data)
          that.setData({
            shopCategory: ''
          })
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  requestShoplist: function (name) {
    var that = this;
    var isKeyword = that.data.isKeyword;
    var categoryId = that.data.curShopCategory ? that.data.curShopCategory:'';
    var data = {};
    var page = that.data.page;
    data.map = 'applet_cake_store_list_new';
    data.cid = categoryId;
    data.page = page;
    data.lng = that.data.curChooseLongitude ? that.data.curChooseLongitude:0;
    data.lat = that.data.curChooseLatitude ? that.data.curChooseLatitude:0;
    if (isKeyword){
      data.cid = '';
      if (name) {
        data.name = name;
      }
    }
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(page);
        console.log(res.data);
        if (res.data.ec == 200) {
          var allArr = [];
          var initArr = that.data.shopList ? that.data.shopList : [];
          var curArr = res.data.data.list;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data.list;
          }
          console.log(allArr);
          that.setData({
            shopList: allArr,
            searchTxt: ''
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
          console.log(that.data.shopList);
        } else {
          if (page <= 0) {
            that.setData({
              shopList: [],
              noMoretip: false,
              showLoading: false
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
  },
  // 计算距离返回列表数组
  getDistanceArr: function ( type, listarr, location){
    var that = this;
    var lat1 = location.lat, lng1 = location.lng;
    for (var i = 0; i < listarr.length; i++) {
      var distance = app.getFlatternDistance(parseFloat(lat1), parseFloat(lng1), parseFloat(listarr[i].lat), parseFloat(listarr[i].lng));
      console.log("根据经纬度拿到的距离" + distance);
      if (!listarr[i].distancenew){
        listarr[i].distancenew = distance.toFixed(2);
      }
    }
    listarr = listarr.sort(app.sortArr('distancenew'));
    console.log("计算距离");
    console.log(listarr);
    that.setData({
      [type]: listarr
    })
  },
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      page: 0,
      noMoretip: false,
      showLoading: true,
      searchTxt:'',
      isKeyword: false,
      curShopCategory:''
    });
    that.onLoad();
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.requestShoplist();
    }
  },
  toggleShopFl:function(e){
    var that = this;
    var shopFlId = e.currentTarget.dataset.id;
    console.log(shopFlId);
    that.setData({
      curShopCategory: shopFlId,
      isKeyword:false,
      shopList:null,
      page: 0,
      noMoretip: false,
      showLoading: true,
    })
    that.requestShoplist();
  },
  seemap: function (e) {
    var latitude = e.currentTarget.dataset.latitude;
    var longitude = e.currentTarget.dataset.longitude;
    var address = e.currentTarget.dataset.address;
    var name = e.currentTarget.dataset.name;
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: '公司地址',
      address: address,
      scale: 18
    })
  },
  makeCall: function () {
    app.makeCall();
  },
  shopDetail:function(e){
    var id = e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: '/subpages/storeDetail/storeDetail?id='+id
    })
  },
  cityLife: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.title;
    console.log(id);
    if (!id) {
      return;
    }
    wx.navigateTo({
      url: '/pages/sameCitylife/sameCitylife?id=' + id + '&title=' + title
    })
  },
  onShareAppMessage: function () {
    console.log(app.setNavtitle('门店列表'));
    var that = this;
    var title = app.setNavtitle('门店列表');
    var shareInfo = app.globalData.shareInfo;
    title = shareInfo.shareTitle ? shareInfo.shareTitle : title;
    var cover = shareInfo.shareCover ? shareInfo.shareCover : '';
    app.getPoint(that);
    return {
      title: title,
      imageUrl: cover,
      path: '/pages/storeListTab/storeListTab'
    }
  }
})
